from django.shortcuts import render
# 导入类
from studentweb.models import Student
# 导入JsonResponse
from django.http import JsonResponse
# 导入Q查询
from django.db.models import Q


def index(request):
    return render(request, 'student/index.html')


def list_values(request):
    """获取所有的学生信息"""
    # 接收传递过来信息的
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    q_sno = request.POST.get('q_sno')
    q_faculty = request.POST.get('q_faculty')
    q_major = request.POST.get('q_major')
    q_status = request.POST.get('q_status')

    # 获取所有的学生信息
    # objs = list(objs.values('sno', 'name', 'gender', 'birthday', 'mobile', 'email', 'address',
    #     #                                          'start_date', 'status', 'major_id', 'major__name', 'faculty_id',
    #     #                                          'faculty__name'))

    # ====== 1. 过滤姓名和学号 ======
    objs = Student.objects.filter(Q(sno__icontains=q_sno) | Q(name__icontains=q_sno))

    # ====== 2. 过滤院系（如果q_faculty不为空） =======
    if q_faculty:
        objs = objs.filter(faculty_id=q_faculty)

    # ====== 3. 过滤专业（如果q_major不为空） =======
    if q_major:
        objs = objs.filter(major_id=q_major)

    # ====== 4. 过滤状态（如果q_status为true） =======
    if q_status == "true":
        objs = objs.filter(status='在校')

    # =======5. list(objs.values()) =========
    objs = list(objs.values('sno', 'name', 'gender', 'birthday', 'mobile', 'email', 'address',
                            'start_date', 'status', 'major_id', 'major__name', 'faculty_id',
                            'faculty__name'))

    # 获取当前页的数据
    one_page_data = objs[(page - 1) * limit: page * limit]

    # 返回
    return JsonResponse({'code': 0, 'count': len(objs), 'data': one_page_data})


def is_sno_exists(request):
    """校验学号是否存在"""
    # 获取学号
    sno = request.POST.get('sno')
    # 判断
    is_exists = Student.objects.filter(sno=sno).exists()
    # 返回
    return JsonResponse({'data': is_exists})


def add_value(request):
    """添加学生"""
    # 接收传递的值
    rec = request.POST
    # 定义一个返回的数据结构
    res = {'status': True}
    # 添加
    try:
        # 创建学生
        Student.objects.create(sno=rec['sno'], name=rec['name'], gender=rec['gender'], birthday=rec['birthday'],
                               mobile=rec['mobile'], email=rec['email'], address=rec['address'],
                               faculty_id=rec['faculty'],major_id=rec['major'], start_date=rec['start_date'],
                               status=rec['status'])
    except Exception as e:
        res['status'] = False
        res['error'] = "数据添加提交到数据库失败，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def edit_value(request):
    # 接收传递的值
    rec = request.POST
    # 定义一个返回的数据结构
    res = {'status': True}
    # 添加
    try:
        # 修改学生
        obj = Student.objects.filter(sno=rec.get('sno')).first()
        # 修改属性
        obj.name = rec.get('name')
        obj.gender = rec['gender']
        obj.birthday = rec['birthday']
        obj.mobile = rec['mobile']
        obj.email = rec['email']
        obj.address = rec['address']
        obj.faculty_id = rec['faculty']
        obj.major_id = rec['major']
        obj.start_date = rec['start_date']
        obj.status = rec['status']
        # 保存
        obj.save()

    except Exception as e:
        res['status'] = False
        res['error'] = "数据添加提交到数据库失败，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def del_value(request):
    # 接收传递的值
    sno = request.POST.get('sno')
    # 修改
    try:
        # 获取当前的对象并删除
        Student.objects.get(sno=sno).delete()

        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改学生信息提交到数据库出现异常，具体原因：' + str(e)})

